import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Input, Drawer } from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { ModalForm, ProFormDigit, ProFormRadio, ProFormSelect, ProFormText, ProFormTextArea } from '@ant-design/pro-form';
import type { ProDescriptionsItemProps } from '@ant-design/pro-descriptions';
import ProDescriptions from '@ant-design/pro-descriptions';
import type { FormValueType } from './UpdateForm';
import UpdateForm from './UpdateForm';
import { rule, addRule, updateRule, removeRule } from '../service';
import type { TableListItem, TableListPagination } from './data';
import UpdateMenuForm from './UpdateMenuForm';
import { updateMenuRole } from 'src/routes/Menu/CRUD/service';
import { useImmer } from 'use-immer';
/**
 * 添加节点
 *
 * @param fields
 */

const handleAdd = async (fields: TableListItem) => {
  const hide = message.loading('正在添加');

  try {
    await addRule({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};
/**
 * 更新节点
 *
 * @param fields
 */

const handleUpdate = async (fields: FormValueType, currentRow?: TableListItem) => {
  const hide = message.loading('正在修改');

  try {
    await updateRule({
      ...currentRow,
      ...fields,
    });
    hide();
    message.success('修改成功');
    return true;
  } catch (error) {
    hide();
    message.error('修改失败请重试！');
    return false;
  }
};



const handleUpdateMenu = async (fields: number[] | undefined, currentRow: number | undefined) => {
  const hide = message.loading('正在修改');

  try {
    await updateMenuRole({
      roleId: currentRow,
      ids: fields,
    });
    //console.log('update menu', fields, currentRow);
    hide();
    message.success('修改成功');
    return true;
  } catch (error) {
    hide();
    message.error('修改失败请重试！');
    return false;
  }
};


/**
 * 删除节点
 *
 * @param selectedRows
 */

const handleRemove = async (selectedRows: TableListItem[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    await removeRule({
      key: selectedRows.map((row) => row.roleId),
    });
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const TableList: React.FC = () => {
  /** 新建窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useImmer(false);
  /** 分布更新窗口的弹窗 */

  const [updateModalVisible, handleUpdateModalVisible] = useImmer(false);
  const [updateMenuModalVisible, handleUpdateMenuModalVisible] = useImmer(false);
  const [showDetail, setShowDetail] = useImmer(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useImmer<TableListItem|undefined>(undefined);
  const [selectedRowsState, setSelectedRows] = useImmer<TableListItem[]>([]);
  /** 国际化配置 */

  const columns: ProColumns<TableListItem>[] = [
    {
      title: '角色ID',
      width: 70,
      dataIndex: 'roleId',
      valueType: 'textarea',
    },
    {
      title: '角色名称',
      width: 90,
      fixed: 'left',
      dataIndex: 'roleName',
      valueType: 'textarea',
    },    
    {
      title: '角色权限字符串',
      width: 120,
      dataIndex: 'roleKey',
      valueType: 'textarea',
    },
    {
      title: '角色顺序',
      width: 70,
      dataIndex: 'roleSort',
      valueType: 'textarea',
    },
    {
      title: '数据范围',
      width: 100,
      dataIndex: 'dataScope',
      valueEnum: {
        1: '全部数据权限',
        2: '自定数据权限',
        3: '本部门数据权限',
        4: '本部门及以下数据权限',
      },
    },
    {
      title: '状态',
      width: 70,
      dataIndex: 'status',
      valueEnum: {
        0: '正常',
        1: '停用',
      },
    },
    {
      title: '删除标记',
      width: 90,
      dataIndex: 'delFlag',
      valueEnum: {
        0: '存在',
        2: '已删除',
      },
    },
    {
      title: '创建者',
      width: 90,
      dataIndex: 'createBy',
      valueType: 'textarea',
    },
    {
      title: '创建时间',
      width: 140,
      sorter: true,
      dataIndex: 'createTime',
      hideInSearch: true,
      valueType: 'dateTime',
    },
    {
      title: '修改者',
      width: 90,
      dataIndex: 'updateBy',
      valueType: 'textarea',
    },
    {
      title: '更新时间',
      width: 140,
      sorter: true,
      dataIndex: 'updateTime',
      hideInSearch: true,
      valueType: 'dateTime',
    },
    {
      title: '备注',
      width: 90,
      dataIndex: 'remark',
      valueType: 'textarea',
    },
    {
      title: '操作',
      fixed: 'right',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {
            //console.log(record)
            handleUpdateModalVisible(true);
            setCurrentRow(record);
          }}
        >
          修改
        </a>,
        <a 
          key="subscribeAlert"
          onClick={() => {
            handleUpdateMenuModalVisible(true);
            setCurrentRow(record);
          }}
        >配置菜单</a>
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<TableListItem, TableListPagination>
        headerTitle="角色列表"
        scroll={{ x: 1700 }}
        actionRef={actionRef}
        rowKey="roleId"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={rule}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项 &nbsp;&nbsp;
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
        </FooterToolbar>
      )}
      <ModalForm
        title="新建角色"
        width="400px"
        open={createModalVisible}
        onFinish={async (value) => {
          const success = await handleAdd(value as TableListItem);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormText
          label="角色名称"
          rules={[{required: true,message: '必填项',},]}
          width="md"
          name="roleName"
        />
        <ProFormText
          label="角色权限字符串"
          rules={[{required: true,message: '必填项',},]}
          width="md"
          name="roleKey"
        />
        <ProFormRadio.Group
          name="status"
          label="Radio.Group"
          rules={[{required: true,message: '必填项',},]}
          options={[
            {
              label: '正常',
              value: 0,
            },
            {
              label: '停用',
              value: 1,
            },

          ]}
        />
        <ProFormSelect
          label="数据范围"
          width="md"
          name="dataScope"
          rules={[{required: true,message: '必填项',},]}
          valueEnum={{
            1: '全部数据权限',
            2: '自定数据权限',
            3: '本部门数据权限',
            4: '本部门及以下数据权限',
          }}
        />
         <ProFormDigit 
          label="显示顺序" 
          name="roleSort"  
          rules={[{required: true,message: '必填项',},]}
          min={0} max={10} 
         />
        <ProFormText
          label="角色备注"
          rules={[{required: true,message: '必填项',},]}
          width="md"
          name="remark"
        />
        <ProFormTextArea width="md" name="desc" />
      </ModalForm>
      <UpdateForm
        onSubmit={async (value) => {
          const success = await handleUpdate(value, currentRow);

          if (success) {
            handleUpdateModalVisible(false);
            setCurrentRow(undefined);

            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateModalVisible(false);
          setCurrentRow(undefined);
        }}
        updateModalVisible={updateModalVisible}
        onVisibleChange={handleUpdateModalVisible}
        values={currentRow || {}}
      />
      <UpdateMenuForm 
         onSubmit={async (value) => {
          const success = await handleUpdateMenu(value, currentRow?.roleId);

          if (success) {
            handleUpdateMenuModalVisible(false);
            setCurrentRow(undefined);

            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateMenuModalVisible(false);
          setCurrentRow(undefined);
        }}
        updateModalVisible={updateMenuModalVisible}
        onVisibleChange={handleUpdateMenuModalVisible}
        values={currentRow || {}}
      />

      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.roleId && (
          <ProDescriptions<TableListItem>
            column={2}
            title={currentRow?.roleId}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.roleId,
            }}
            columns={columns as ProDescriptionsItemProps<TableListItem>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
